/** Test Main function 2
 *
 *  Test Main function 2. Test the MPIReader and MPIWriter.
 *
 *  @author : huicong
 *  @date : 2008-10-28
 *
 */

#include "BCMI_Frame.h"
#include "BasicDataStructure.h"
#include "MPIReader.h"
#include "MPIWriter.h"
#include "BasicHeader.h"
#include "FrameTask.h"

#include <iostream>

using namespace std;
using namespace bcmi_frame;

const static UINT LEN = 100;

class TestClass: public bcmi_frame::BasicDataStructure
{
public:

    INT a , b , c;
    INT arr[LEN];

    TestClass()
    {
        a = 0;
        b = 0; 
        c = 0;
        memset(arr, 0 , sizeof(INT) * LEN );
    }

    HRESULT serialize(INOUT StreamWriter &_streamWriter)
    {
        HRESULT hr = H_OK;
        UINT _actualSize;
        _streamWriter.write(&a, sizeof(INT), _actualSize);
        _streamWriter.write(&b, sizeof(INT), _actualSize);
        _streamWriter.write(&c, sizeof(INT), _actualSize);
        _streamWriter.write(arr, sizeof(INT) * LEN, _actualSize);
        return hr;
    }

    HRESULT deSerialize(INOUT StreamReader &_streamReader)
    {
        HRESULT hr = H_OK;
        UINT _actualSize;
        _streamReader.read(&a, sizeof(INT), _actualSize);
        _streamReader.read(&b, sizeof(INT), _actualSize);
        _streamReader.read(&c, sizeof(INT), _actualSize);
        _streamReader.read(arr, sizeof(INT) * LEN, _actualSize);
        return hr;
    }
};

INT main2(INT argc, CHAR **argv)
{
    MPI_Init(&argc, &argv);

    INT my_rank;
    MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
    if (0 == my_rank) // 0 does
    {
        FrameClock _clock;
        LogRecorder _log("0.log", &_clock);
        TestClass tc;
        MPIWriter writer(1, &_log);
        tc.a = 1;
        tc.b = 2;
        tc.c = 3;
        for (INT i = 0; i < LEN; ++i)
        {
            tc.arr[i] = i;
        }
        tc.serialize(writer);
        writer.putBufferPool();
        cout << "0 process has send the TestClass a = 1, b = 2, c = 3" << endl;;
        cout << "0 process long buffer : ";
        for (UINT i = 0; i < LEN; ++i)
        {
            cout << tc.arr[i] << " ";
        }
        cout << endl;
    }
    else // 1 does
    {
        FrameClock _clock;
        LogRecorder _log("1.log", &_clock);
        TestClass tc;
        MPIReader reader(0, &_log);
        reader.getBufferPool();
        tc.deSerialize(reader);
        cout << "1 process has recv the TestClass a = "
            << tc.a << ", b = "
            << tc.b << ", c = "
            << tc.c << endl;
        cout << "1 process long buffer : ";
        for (UINT i = 0; i < LEN; ++i)
        {
            cout << tc.arr[i] << " ";
        }
        cout << endl;
    }
    MPI_Finalize();
    return 0;
}
